// 购物车样式

(function() {
	let oCartTable = document.querySelector('.cart-table');
	let oShopcarttb = document.querySelector('.shopcart-tb');
	let oContinueShop = document.querySelector('.continue-shop');
	let oNowSettlementBtn = document.querySelector('.now-settlement-btn');


	// 校验
	if (!localStorage.getItem('token') || !localStorage.getItem('username')) {
		alert('非法登录');
		return;
	}
	// 请求数据
	yzb.ajax({
		method: 'post',
		url: BASE_URL + '/api_cart',
		data: {
			status: 'viewcart',
			userId: localStorage.getItem('token')
		},
		success(res) {
			if (res.code != 0) {
				console.log(res);
				return;
			};

			// 组装dom
			let goodsArr = res.data;
			// 验证
			if (goodsArr.length == 0) {
				oShopcarttb.innerHTML = '暂无商品...';
				// 调用总价方法
				getPriceAll();
				return;
			};
			// 调用总价方法
			getPriceAll();
			// 结构
			let str = `
			<tr class="shopcart-tr" id="shopcart-tr1">
				<td id="shopcart-td1">
					<input type="checkbox" group="cart-g" class='check-all'/>
					<span>全选</span>
				</td>
				<td>
					<p>良品</p>
				</td>
				<td>
					<p>数量</p>
				</td>
				<td>
					<p>单价（元）</p>
				</td>
				<td>
					<p>小计（元）</p>
				</td>
				<td>
					<p>操作</p>
				</td>
			</tr>
			`;

			// 遍历
			goodsArr.forEach(item => {
				str += `
				<tr class="shopcart-tr">
					<td>
						<input type="checkbox" class='check' goods-id="${item.goods_id}"/>
						<a href=""><img src="${item.goods_thumb}" class="cart-img" /></a>
					</td>
					<td>
						<a href="" class="cart-dec">
							<p>${item.goods_name}</p>
						</a>
					</td>
					<td>
						<span class='reduce' goods-id="${item.goods_id}" price="${item.price}">-</span>
						<input type="text" value="${item.goods_number}" readonly class="cart-in" />
						<span class="add" goods-id="${item.goods_id}" price="${item.price}">+</span>
					</td>
					<td>
						${item.price}
					</td>
					<td>
						<p><span>${item.price * item.goods_number}</span></p>
					</td>
					<td>
						<a href="javascript:;" class="delete" goods-id="${item.goods_id}">删除</a>
					</td>
				</tr>
				`;
			});
			// 添加到页面
			oShopcarttb.innerHTML = str;

			// 给整个表格添加点击事件
			oShopcarttb.onclick = function(e) {

				// 获取类名
				let clsName = e.target.className;
				// 验证

				// 点击全选
				if (clsName == 'check-all') {
					// 获取页面中所有单个商品
					let aCheck = document.querySelectorAll('.check');
					aCheck.forEach(item => {
						item.checked = e.target.checked;
						// 添加标记
						item.setAttribute('check', e.target.checked ? 'checked' : '');
					});
					// 调用总价方法
					getPriceAll();
				};

				// 点击单选
				if (clsName == 'check') {
					// 添加标记
					e.target.setAttribute('check', e.target.checked ? 'checked' : '');
					// 调用总价方法
					getPriceAll();
				};

				// 点击减或加
				if (clsName == 'reduce' || clsName == 'add') {

					let numDom = null;
					let num = null;
					let subtotalDom = e.target.parentNode.nextElementSibling.nextElementSibling;

					if (clsName == 'reduce') {
						numDom = e.target.nextElementSibling;
						num = parseInt(e.target.nextElementSibling.value);
						num--;
						num = num <= 1 ? 1 : num;
					} else if (clsName == 'add') {
						numDom = e.target.previousElementSibling;
						num = parseInt(e.target.previousElementSibling.value);
						num++;
						num = num >= 10 ? 10 : num;
					}
					
					// 更新后台数据
					yzb.ajax({
						method: 'post',
						url: BASE_URL + '/api_cart',
						data: {
							status: 'addcart',
							userId: localStorage.getItem('token'),
							goodsId: e.target.getAttribute('goods-id'),
							goodsNumber: num
						},
						success(res) {
							if (res.code != 0) {
								console.log(res);
								return;
							};

							// 更新前端
							numDom.value = num;
							subtotalDom.innerHTML = num * parseFloat(e.target.getAttribute('price'));
							// 调用总价方法
							getPriceAll();
						}
					});
				};

				// 点击删除
				if (clsName == 'delete') {
					// 删除后台数据
					yzb.ajax({
						method: 'post',
						url: BASE_URL + '/api_cart',
						data: {
							status: 'delcart',
							userId: localStorage.getItem('token'),
							goodsId: e.target.getAttribute('goods-id')
						},
						success(res) {
							if (res.code != 0) {
								console.log(res);
								return;
							};
					
							// 更新前端
							e.target.parentNode.parentNode.remove();
							// 调用总价方法
							getPriceAll();
						}
					});
				};
			};

			// 总价方法
			function getPriceAll() {
				// 选到所有check的自定义属性
				let aCheckAll = document.querySelectorAll('[check="checked"]');
				let oPriceAllDom = document.querySelector('.price-all');
				let priceAll = 0;
				aCheckAll.forEach(item => {
					let numDom = item.parentNode.nextElementSibling.nextElementSibling.children[1];
					let priceDom = item.parentNode.nextElementSibling.nextElementSibling.nextElementSibling;
					let num = parseFloat(numDom.value);
					let price = parseFloat(priceDom.innerHTML);
					priceAll += price * num;
				});

				// 设置
				oPriceAllDom.innerHTML = `
				<span>良品总价</span>
				<span>/</span>
				<span>￥${priceAll}</span>
				`;
			};
			
			// 点击立即结算按钮
			oNowSettlementBtn.onclick = function() {
				// 选到所有check的自定义属性
				let aCheckAll = document.querySelectorAll('[check="checked"]');
				// 获取id号
				let arrGoodsId = [];
				aCheckAll.forEach(item=>arrGoodsId.push(item.getAttribute('goods-id')));
				// 验证
				if(arrGoodsId.length == 0){
					alert('请选择商品');
					return;
				};
				// 加入结算清单 跳转到订单页面
				yzb.ajax({
					method:'post',
					url:BASE_URL + '/api_settlement',
					data:{
						status:'addsettlement',
						userId:localStorage.getItem('token'),
						from:'cart',
						goodsId:arrGoodsId.join('&')
					},
					success(res){
						if(res.code != 0){
							console.log(res);
							return;
						};
						// 加入结算成功
						alert('加入结算成功');
						// 跳转到订单页面
						location.href = 'order.html';
					}
				})
			};
			
			// 继续购物
			oContinueShop.onclick = function() {
				window.location.href = 'classify.html';
			}
		}
		
	})
})();